package com.topcent.tioxyc.consumer;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.ImgProcessEntity;
import com.topcent.tioxyc.pojo.vo.ImgProcessEntityResult;
import com.topcent.tioxyc.pojo.vo.InformationDateVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * @author: 陈百万
 * @date: 2025/3/12 15:41
 * @Description: 图片处理消费类
 */

@Component
@RabbitListener(queues = "imgProcess")
@Slf4j
public class ImgProcessConsumer {

    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    // 配置参数（根据实际测量调整）
    private static final int TARGET_X = 333;
    private static final int TARGET_Y = 4000;
    private static final String FONT_NAME = "MiSans";
    private static final int FONT_SIZE = 180;  // 增大字号

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 在这里执行具体的业务逻辑

            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            String op = payloadJSON.getStr("op");
            String data = payloadJSON.getStr("data");

            if (DATA_CREATE.equals(op)) {
                // 区分 修改图片型号 还是 加拓臣LOGO
                ImgProcessEntity imgProcessEntity = JSONUtil.toBean(data, ImgProcessEntity.class);

                updateImgModel(imgProcessEntity);

                /*if (imgProcessEntity.get_widget_1741762126396().equals("修改图片型号")) {
                    log.info("图片入参参数：{}", imgProcessEntity);
                    updateImgModel(imgProcessEntity);
                }else {
                    // 加拓臣LOGO
                    addLogo(imgProcessEntity);
                }*/
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    // 2、加拓臣LOGO
    private BufferedImage addLogo(ImgProcessEntity imgProcessEntity) {
        try {
            Header[] headers = ConnmeUtils.createHeaders();
            String appId = "667e34f0f58dbce6ca246f47";
            String entryId = "67d12e4eefc148fec9e12a93";

            // 1. 加载图片并打印基本信息
            // 获取 URL
            URL imageUrl = new URL(imgProcessEntity.getMx().getFirst().get_widget_1747808645559().getFirst().getUrl());
            // 通过 URL 打开输入流
            InputStream inputStream = imageUrl.openStream();
            // 读取图片
            BufferedImage image = ImageIO.read(inputStream);
            if (image != null) {
                // 图片读取成功
                System.out.println("图片读取成功！");
            } else {
                // 图片读取失败
                System.out.println("无法读取图片！");
                return null;
            }
            System.out.println("图片尺寸: " + image.getWidth() + "x" + image.getHeight());
            // 图标
            String iconPath = "/www/wwwroot/tupian/LOGO.png";
            BufferedImage icon = ImageIO.read(new File(iconPath));

            // 比例缩放计算
            int originalWidth = icon.getWidth();
            int originalHeight = icon.getHeight();
            float scaleRatio = Math.min(
                    (image.getWidth() * 0.4f) / originalWidth,
                    (image.getHeight() * 0.4f) / originalHeight
            );
            int scaledWidth = (int) (originalWidth * scaleRatio);
            int scaledHeight = (int) (originalHeight * scaleRatio);

            // 高质量缩放
            BufferedImage scaledIcon = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = scaledIcon.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2d.drawImage(icon, 0, 0, scaledWidth, scaledHeight, null);
            g2d.dispose();

            // 左上角定位
            int margin = 333;
            int x = margin;
            int y = margin;

            // 边界检测
            if (x + scaledWidth > image.getWidth() || y + scaledHeight > image.getHeight()) {
                throw new IllegalArgumentException("Logo尺寸超出画布范围");
            }

            Graphics2D graphics = image.createGraphics();

            // 设置透明度混合（参考网页2的AlphaComposite用法）
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));

            // 绘制缩放后的图标（网页2中的drawImage方法扩展）
            graphics.drawImage(scaledIcon,
                    x,
                    y,
                    scaledWidth,
                    scaledHeight,
                    null);

            graphics.dispose();
            return image;
        }catch (Exception e) {
            log.error("处理失败：{}", e.getMessage());
        }
        return null;
    }

    // 1、修改图片型号
    private void updateImgModel(ImgProcessEntity imgProcessEntity) {
        try {
            ImgProcessEntityResult entityResult =new ImgProcessEntityResult();
            List<ImgProcessEntityResult.subformResult> subformResultList = new ArrayList<>();
            ImgProcessEntityResult.subformResult subformResult = new ImgProcessEntityResult.subformResult();

            Header[] headers = ConnmeUtils.createHeaders();
            String appId = "64ee9c37ee0a2c0007bc7afc";
            String entryId = "650ab93189d8223244d5b4cc";

            String appId1 = "64ee9c37ee0a2c0007bc7afc";
            String entryId1 = "6694810ddb471c31112b395d";
            String oldUrl = imgProcessEntity.getMx().getFirst().get_widget_1747808645559().getFirst().getUrl();
            String newUrl = imgProcessEntity.getMx().getFirst().get_widget_1747808645559().getFirst().getUrl();

            // 1. 加载图片并打印基本信息
            // 获取 URL
            URL imageUrl = new URL(oldUrl);
            URL imageUrlNew = new URL(newUrl);
            // 通过 URL 打开输入流
            InputStream inputStream = imageUrlNew.openStream();
            InputStream inputStreamOld = imageUrl.openStream();
            // 读取图片
            // 1. 加载原始图片并添加LOGO
            BufferedImage image = addLogo(imgProcessEntity);
            BufferedImage imageOld = ImageIO.read(inputStreamOld);
            if (image != null) {
                // 图片读取成功
                System.out.println("图片读取成功！");
            } else {
                // 图片读取失败
                System.out.println("无法读取图片！");
                return;
            }
            //BufferedImage image = ImageIO.read(new File(imgProcessEntity.get_widget_1741763346076().getFirst().getUrl()));
            System.out.println("图片尺寸: " + image.getWidth() + "x" + image.getHeight());
            // 2. 创建图形上下文
            Graphics2D g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 水印
            BufferedImage watermark = loadWatermark();
            watermark = scaleWatermark(watermark, image.getWidth(), image.getHeight()); // 缩放到图片的70%
            drawWatermark(g, image, watermark);

            // 英文
            BufferedImage watermarkE = loadWatermarkE();
            watermarkE = scaleWatermarkE(watermarkE, image.getWidth(), image.getHeight()); // 缩放到图片的70%
            drawWatermarkE(g, image, watermarkE);

            // 3. 字体配置（带系统验证）
            Font font = checkFontAvailable(FONT_NAME, Font.BOLD, FONT_SIZE);
            g.setFont(font);
            System.out.println("实际使用字体: " + font.getFontName() + " 大小: " + font.getSize());

            // 4. 设置白色文字
            g.setColor(Color.WHITE);  // 修改为白色

            // 5. 调试模式：绘制背景框
            //debugTextPosition(g, TARGET_X, TARGET_Y, request.getNewCode());

            String wenzi = imgProcessEntity.getMx().getFirst().getImgnames();
            // 6. 正式绘制
            clearTextBackground(g, TARGET_X, TARGET_Y, wenzi);

            // 上传图片到简道云
            // 随机数
            String transactionId = IdUtil.randomUUID();

            // Step 1: Get upload tokenvb
            JSONObject uploadToken = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(0);
            JSONObject uploadToken1 = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(1);
            JSONObject uploadToken2 = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(2);
            JSONObject uploadToken3 = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(3);
            JSONObject uploadToken4 = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(4);

            JSONObject uploadTokenDumpImg = getUploadToken(appId1, entryId1, transactionId, headers).getJSONObject(0);

            // Step 2: Process image (resize, replace text, etc.)
            String imageName = ConnmeUtils.getFileNameWithoutExtension(imgProcessEntity.getMx().getFirst().get_widget_1747808645559().getFirst().getName());
            File outputImage = new File("/www/wwwroot/tupian/" + imageName + ".png");
            File outputImageOld = new File("/www/wwwroot/tupian/" + imageName + ".png");

            // 插图
            String url563 = CollectionUtils.isNotEmpty(imgProcessEntity.getMx().getFirst().get_widget_1700546383563()) ? imgProcessEntity.getMx().getFirst().get_widget_1700546383563().getFirst().getUrl() : null;
            String urlAppendixTu = CollectionUtils.isNotEmpty(imgProcessEntity.getMx().getFirst().getAppendix_tu()) ? imgProcessEntity.getMx().getFirst().getAppendix_tu().getFirst().getUrl() : null;
            String url806 = CollectionUtils.isNotEmpty(imgProcessEntity.getMx().getFirst().get_widget_1722483118806()) ? imgProcessEntity.getMx().getFirst().get_widget_1722483118806().getFirst().getUrl() : null;
            if (StringUtils.isNotBlank(url563)) {
                List<String> list563 = new ArrayList<>();
                URL imageUrl563 = new URL(url563);
                InputStream inputStream563 = imageUrl563.openStream();
                BufferedImage image563 = ImageIO.read(inputStream563);
                String imageName563 = ConnmeUtils.getFileNameWithoutExtension(imgProcessEntity.getMx().getFirst().get_widget_1700546383563().getFirst().getName());
                File outputImage563 = new File("/www/wwwroot/tupian/" + imageName563 + ".png");
                ImageIO.write(image563, "png", outputImage563);
                String imageKey563 = uploadImage(uploadToken2.getStr("url"), uploadToken2.getStr("token"), outputImage563);
                list563.add(imageKey563);
                subformResult.set_widget_1700546383563(list563);
            }
            if (StringUtils.isNotBlank(urlAppendixTu)) {
                List<String> listAppendixTu = new ArrayList<>();
                URL imageUrlurlAppendixTu = new URL(urlAppendixTu);
                InputStream inputStreamurlAppendixTu = imageUrlurlAppendixTu.openStream();
                BufferedImage imageurlAppendixTu = ImageIO.read(inputStreamurlAppendixTu);
                String imageNameAppendixTu = ConnmeUtils.getFileNameWithoutExtension(imgProcessEntity.getMx().getFirst().getAppendix_tu().getFirst().getName());
                File outputImageurlAppendixTu = new File("/www/wwwroot/tupian/" + imageNameAppendixTu + ".png");
                ImageIO.write(imageurlAppendixTu, "png", outputImageurlAppendixTu);
                String imageKeyurlAppendixTu = uploadImage(uploadToken3.getStr("url"), uploadToken3.getStr("token"), outputImageurlAppendixTu);
                listAppendixTu.add(imageKeyurlAppendixTu);
                subformResult.setAppendix_tu(listAppendixTu);
            }
            if (StringUtils.isNotBlank(url806)) {
                List<String> list806 = new ArrayList<>();
                URL imageUrl806 = new URL(url806);
                InputStream inputStream806 = imageUrl806.openStream();
                BufferedImage image806 = ImageIO.read(inputStream806);
                String imageName806 = ConnmeUtils.getFileNameWithoutExtension(imgProcessEntity.getMx().getFirst().get_widget_1722483118806().getFirst().getName());
                File outputImage806 = new File("/www/wwwroot/tupian/" + imageName806 + ".png");
                ImageIO.write(image806, "png", outputImage806);
                String imageKey806 = uploadImage(uploadToken4.getStr("url"), uploadToken4.getStr("token"), outputImage806);
                list806.add(imageKey806);
                subformResult.set_widget_1722483118806(list806);
            }
            // Step 3: Save the processed image
            ImageIO.write(image, "png", outputImage);

            // Step 4: Upload image
            String imageKey = uploadImage(uploadToken.getStr("url"), uploadToken.getStr("token"), outputImage);
            String imageKeyDumpImg = uploadImage(uploadTokenDumpImg.getStr("url"), uploadTokenDumpImg.getStr("token"), outputImage);

            ImageIO.write(imageOld, "png", outputImageOld);
            String oldUrl1 = uploadImage(uploadToken1.getStr("url"), uploadToken1.getStr("token"), outputImageOld);
            log.info("图片入参参数oldUrl：{}", oldUrl);
            List<String> imgList = new ArrayList<>();imgList.add(imageKey);
            List<String> imgListDumpImg = new ArrayList<>();imgListDumpImg.add(imageKeyDumpImg);
            List<String> imgListOld = new ArrayList<>();imgListOld.add(oldUrl1);
            subformResult.setAppendix(imgList);
            subformResult.set_widget_1754458627927(imgList);
            subformResult.set_widget_1747808645559(imgListOld);
            subformResult.setDisabled(imgProcessEntity.getMx().getFirst().getDisabled());
            subformResult.setImgnames(imgProcessEntity.getMx().getFirst().getImgnames());
            subformResult.setSub_process_code(imgProcessEntity.getMx().getFirst().getSub_process_code());
            subformResult.setStyle(imgProcessEntity.getMx().getFirst().getStyle());
            subformResult.setProduct_name(imgProcessEntity.getMx().getFirst().getProduct_name());
            subformResult.setProduct_grade(imgProcessEntity.getMx().getFirst().getProduct_grade());
            subformResult.setProduct_key_points(imgProcessEntity.getMx().getFirst().getProduct_key_points());
            subformResult.setProvided_samples(imgProcessEntity.getMx().getFirst().getProvided_samples());
            subformResult.setUnit(imgProcessEntity.getMx().getFirst().getUnit());
            subformResult.setShooting_requirements_remarks(imgProcessEntity.getMx().getFirst().getShooting_requirements_remarks());
            subformResult.setNeed_to_include_in_catalog(imgProcessEntity.getMx().getFirst().getNeed_to_include_in_catalog());
            subformResult.setSupplier_material_available(imgProcessEntity.getMx().getFirst().getSupplier_material_available());
            subformResult.setSupplier_material_storage_path(imgProcessEntity.getMx().getFirst().getSupplier_material_storage_path());
            subformResult.setSpecifications_model(imgProcessEntity.getMx().getFirst().getSpecifications_model());
            subformResult.setTransfer(imgProcessEntity.getMx().getFirst().getTransfer());
            subformResultList.add(subformResult);
            entityResult.setMx(subformResultList);
            // Step 5: Update form with image key
            updateFormData(imgProcessEntity, appId, entryId, transactionId, headers, entityResult);

            // 新插入  信息库营销资料上传申请
            InformationDateVO.infoDetailResult infoDetailResult = new InformationDateVO.infoDetailResult();
            infoDetailResult.set_widget_1721008397750(imgProcessEntity.getMx().getFirst().getImgnames());
            infoDetailResult.set_widget_1721008397751(imgProcessEntity.getMx().getFirst().getStyle());
            infoDetailResult.set_widget_1753952264330(imgListDumpImg);
            infoDetailResult.set_widget_1757310507144("程序新增");
            // 新增
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", appId1);
            parameter.put("entry_id", entryId1);
            parameter.put("transaction_id", transactionId);
            parameter.put("data", ConnmeUtils.convertEntityToMap(infoDetailResult));
            infoDetailResult.set_id(null);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
        } catch (Exception e) {
            log.error("处理失败：{}", e.getMessage());
        }
    }

    // 1、1字体可用性检查
    private Font checkFontAvailable(String fontName, int style, int size) {
        // Linux 上字体文件的存放路径，根据实际情况改
        String fontFilePath = "/www/wwwroot/default/MiSans-Semibold_0.ttf";
        try {
            // 从 Linux 本地路径读取字体文件
            File fontFile = new File(fontFilePath);
            if (fontFile.exists()) {
                FileInputStream fontStream = new FileInputStream(fontFile);
                Font customFont = Font.createFont(Font.TRUETYPE_FONT, fontStream)
                        .deriveFont(style, size);
                fontStream.close();
                return customFont;
            } else {
                log.warn("Linux 上指定路径的字体文件不存在：{}", fontFilePath);
            }
        } catch (FontFormatException | IOException e) {
            log.warn("自定义字体加载失败，fallback 到系统字体", e);
        }

        // 系统字体 fallback 逻辑（和之前一样）
        String[] availableFonts = GraphicsEnvironment
                .getLocalGraphicsEnvironment()
                .getAvailableFontFamilyNames();
        if (Arrays.asList(availableFonts).contains(fontName)) {
            return new Font(fontName, style, size);
        }
        log.info("警告：字体{}不可用，使用默认字体", fontName);
        return new Font("SansSerif", style, size);
    }

    private void clearTextBackground(Graphics2D g, int x, int y, String text) {
        FontMetrics metrics = g.getFontMetrics();

        // 原始背景参数（保持不变）
        int padding = 10;
        int bgWidth = metrics.stringWidth(text) + padding * 2 + 222;
        int bgHeight = metrics.getHeight() + padding * 2 + 100;
        int arcSize = 100;
        int bgX = x - padding / 2 - 5;
        int bgY = y - metrics.getAscent() - padding / 2 - 2;

        // 文字放大系数（1.2表示放大20%）
        float scaleFactor = 1.15f;

        // 创建缩放后的字体（关键修改）
        Font originalFont = g.getFont();
        Font scaledFont = originalFont.deriveFont(originalFont.getSize2D() * scaleFactor);
        g.setFont(scaledFont);

        // 重新计算缩放后的文字尺寸
        FontMetrics scaledMetrics = g.getFontMetrics();
        int scaledTextWidth = scaledMetrics.stringWidth(text);
        int scaledTextHeight = scaledMetrics.getHeight();

        // 保持原始背景绘制（保持不变）
        g.setColor(new Color(22, 185, 223));
        g.fillRoundRect(bgX, bgY, bgWidth, bgHeight, arcSize, arcSize);

        // 计算缩放后的文字位置（自动居中）
        int textX = bgX + (bgWidth - scaledTextWidth) / 2;
        int textY = bgY + (bgHeight - scaledTextHeight) / 2 + scaledMetrics.getAscent();

        // 绘制放大后的文字
        g.setColor(Color.WHITE);
        g.drawString(text, textX, textY);

        // 恢复原始字体（避免影响后续绘制）
        g.setFont(originalFont);
    }

    /**
     * 生成token 和 url
     *
     * @param appId
     * @param entryId
     * @param transactionId
     * @return
     */
    public JSONArray getUploadToken(String appId, String entryId, String transactionId, Header[] headers) {
        Map<String, Object> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("entry_id", entryId);
        params.put("transaction_id", transactionId);

        String jsonSale = JSONUtil.toJsonStr(params);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/file/get_upload_token", headers, jsonSale);
        System.out.println("接口返回: token and url ========》》》 " + jdySale);
        // 直接从响应中获取 token_and_url_list
        JSONArray tokenAndUrlList = jdySale.getJSONArray("token_and_url_list");

        if (tokenAndUrlList != null && !tokenAndUrlList.isEmpty()) {
            // 如果数组不为空，获取第一个元素
            return tokenAndUrlList;  // 返回 token 和 url
        } else {
            // 如果数组为空，抛出异常或返回 null
            throw new RuntimeException("No tokens available in token_and_url_list");
        }

    }

    /**
     * 生成 key
     * @param uploadUrl
     * @param token
     * @param imageFile
     * @return
     */
    public String uploadImage(String uploadUrl, String token, File imageFile) {
        String response = HttpRequest.post(uploadUrl)
                .form("token", token)
                .form("file", imageFile, imageFile.getName())  // Upload the image file
                .form("filename", imageFile.getName())  // The filename
                .execute()
                .body();

        JSONObject jsonResponse = JSONUtil.parseObj(response);
        System.out.println("生成key ========++++++》》》 " + jsonResponse);
        return jsonResponse.getStr("key");  // 返回的 key
    }

    /**
     * 上传简道云
     * @param appId
     * @param entryId
     * @param entityResult
     * @param transactionId
     */
    public void updateFormData(ImgProcessEntity entity, String appId, String entryId, String transactionId, Header[] headers , ImgProcessEntityResult entityResult) {
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", appId);
        parameterInster.put("entry_id", entryId);
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", entity.get_id());
        parameterInster.put("transaction_id", transactionId);
        entityResult.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(entityResult));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        log.info("图片处理的数据{}", jsonSalee);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    private BufferedImage loadWatermark() throws IOException {
        String watermarkPath = "/www/wwwroot/tupian/watermark.png"; // 水印图片路径
        return ImageIO.read(new File(watermarkPath));
    }
    private BufferedImage loadWatermarkE() throws IOException {
        String watermarkPath = "/www/wwwroot/tupian/english.png"; // 水印图片路径
        return ImageIO.read(new File(watermarkPath));
    }

    /**
     * 缩放水印图片，确保不超过目标尺寸（如图片的50%）
     */
    private BufferedImage scaleWatermark(BufferedImage watermark, int maxWidth, int maxHeight) {
        int width = watermark.getWidth();
        int height = watermark.getHeight();

        // 计算缩放比例，避免水印超过图片的50%
        float scaleX = (float) maxWidth / width;
        float scaleY = (float) maxHeight / height;
        float scale = Math.min(scaleX, scaleY); // 取较小比例，保持宽高比

        /*int newWidth = (int) (width * scale)  + 666;
        int newHeight = (int) (height * scale)  + 100;*/
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);

        // 高质量缩放（抗锯齿、双三次插值）
        BufferedImage scaled = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaled.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(watermark, 0, 0, newWidth, newHeight, null);
        g2d.dispose();

        return scaled;
    }

    private BufferedImage scaleWatermarkE(BufferedImage watermark, int maxWidth, int maxHeight) {
        int width = watermark.getWidth();
        int height = watermark.getHeight();

        // 计算缩放比例，避免水印超过图片的50%
        float scaleX = (float) maxWidth / width;
        float scaleY = (float) maxHeight / height;
        float scale = Math.min(scaleX, scaleY); // 取较小比例，保持宽高比

        int newWidth = (int) (width * scale) - 1888;
        int newHeight = (int) (height * scale) - 1433;

        // 高质量缩放（抗锯齿、双三次插值）
        BufferedImage scaled = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaled.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(watermark, 0, 0, newWidth, newHeight, null);
        g2d.dispose();

        return scaled;
    }

    private void drawWatermark(Graphics2D g, BufferedImage image, BufferedImage watermark) {
        // 1. 先缩放水印到图片的50%以内（maxWidth/maxHeight设为图片的一半）
        BufferedImage scaledWatermark = scaleWatermark(watermark, image.getWidth() / 2, image.getHeight() / 2);

        // 2. 计算居中坐标（确保缩放后尺寸有效，避免负数）
        int x = (image.getWidth() - scaledWatermark.getWidth()) / 2;
        int y = (image.getHeight() - scaledWatermark.getHeight()) / 2;
        x = Math.max(x, 0); // 左边界不小于0
        y = Math.max(y, 0); // 上边界不小于0

        // 3. 设置透明度并绘制（半透明示例）
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));
        g.drawImage(scaledWatermark, x, y, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); // 恢复默认
    }

    private void drawWatermarkE(Graphics2D g, BufferedImage image, BufferedImage watermark) {
        // 1. 先缩放水印到图片的50%以内（maxWidth/maxHeight设为图片的一半）
        BufferedImage scaledWatermark = scaleWatermarkE(watermark, image.getWidth() / 2, image.getHeight() / 2);

        // 2. 计算居中坐标（确保缩放后尺寸有效，避免负数）
        int x = (image.getWidth() - scaledWatermark.getWidth()) / 2 - 1800;
        int y = (image.getHeight() - scaledWatermark.getHeight()) / 2 + 1950;
        x = Math.max(x, 0); // 左边界不小于0
        y = Math.max(y, 0); // 上边界不小于0

        // 3. 设置透明度并绘制（半透明示例）
        g.drawImage(scaledWatermark, x, y, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); // 恢复默认
    }
}
